package com.beiming.sensor

import android.hardware.Sensor
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView

class SensorAdapter(private val sensors: List<Sensor>) :
    RecyclerView.Adapter<SensorAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val name: TextView = view.findViewById(R.id.tv_name)
        val typeName: TextView = view.findViewById(R.id.tv_type_name)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_sensor, parent, false)
        val viewHolder = ViewHolder(view)
        viewHolder.name.setOnClickListener {
            val position = viewHolder.adapterPosition
            val sensor = sensors[position]
            Toast.makeText(
                parent.context,
                "you clicked view ${sensor.name}",
                Toast.LENGTH_SHORT
            ).show()
        }
        return viewHolder
    }

    override fun getItemCount() = sensors.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val sensor = sensors[position]
        holder.name?.text = "name:${sensor.name}(${getSensorNameByType(sensor.type)})"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            holder.typeName?.text = "type:${sensor.stringType}"
        }
    }

    companion object {

        @JvmStatic
        fun getSensorNameByType(type: Int) =
            when (type) {
                Sensor.TYPE_ORIENTATION -> "方向传感器"
                Sensor.TYPE_ACCELEROMETER -> "加速度传感器"
                Sensor.TYPE_GYROSCOPE -> "陀螺仪传感器"
                Sensor.TYPE_MAGNETIC_FIELD -> "磁场传感器"
                Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED -> "磁场传感器(无校准)"
                Sensor.TYPE_GRAVITY -> "重力传感器"
                Sensor.TYPE_LINEAR_ACCELERATION -> "线性加速度传感器"
                Sensor.TYPE_AMBIENT_TEMPERATURE -> "环境温度传感器"
                Sensor.TYPE_LIGHT -> "光传感器"
                Sensor.TYPE_PRESSURE -> "空气压力传感器"
                Sensor.TYPE_PROXIMITY -> "距离传感器"
                Sensor.TYPE_RELATIVE_HUMIDITY -> "探测结露点、相对和绝对湿度传感器"
                Sensor.TYPE_ROTATION_VECTOR -> "运动检测和旋转检测传感器"
                Sensor.TYPE_TEMPERATURE -> "温度传感器"
                Sensor.TYPE_GAME_ROTATION_VECTOR -> "游戏旋转矢量传感器"
                Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR -> "地磁旋转矢量传感器"
                Sensor.TYPE_STEP_COUNTER -> "计步器"
                Sensor.TYPE_STEP_DETECTOR -> "步伐检测器"
                else -> "Unknown"
            }
    }
}